/**
 * @Title: UserInfoController.java
 * @Package com.zll.ccp.controller
 * @author zhanglinlu
 * @date 2019年5月1日 下午4:29:13
 */
package com.zll.ccp.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import com.zll.ccp.annotation.RequireOwn;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.zll.ccp.constants.Constant;
import com.zll.ccp.model.User;
import com.zll.ccp.model.UserInfo;
import com.zll.ccp.service.ILoginService;
import com.zll.ccp.service.IUserInfoService;

/**
 * @ClassName: UserInfoController
 * @Description: 个人中心
 * @author zhanglinlu
 * @date 2019年5月1日 下午4:29:13
 * 
 */
@Controller
public class UserInfoController {
    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private ILoginService loginService;

    private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoController.class);

    /**
     * @Title: userInfo
     * @Description: 去个人中心
     * @return 个人中心页面
     */
    @RequestMapping("/userInfo")
    public String userInfo() {
        return "userInfo";
    }

    /**
     * @param userName
     * @return
     * @Title: getUserInfoByUserName
     * @Description: 根据用户名
     */
    @RequestMapping("/userinfo/{userName}")
    @ResponseBody
    public Object getUserInfoByUserName(@PathVariable String userName, HttpSession session) {
        String userName1 = session.getAttribute("userName").toString();
        if (!StringUtils.equals(userName1, userName)) {
            JSONObject result = new JSONObject();
            result.put("success", false);
            result.put("message", "无权限");
            return result;
        }
        return userInfoService.getUserInfoByUserName(userName);
    }

    /**
     * @Title: saveUserInfo
     * @Description: 保存用户提交的用户信息（新增或更新）
     * @param userInfo 用户信息
     * @return 执行结果
     */
    @RequestMapping("/saveuserinfo")
    @ResponseBody
    public Object saveUserInfo(@RequestBody UserInfo userInfo, HttpSession session) {
        JSONObject result = new JSONObject();
        String newUserName = userInfo.getUserName();
        // 验证
        if (StringUtils.isBlank(newUserName)) {
            result.put("success", false);
            result.put("message", "用户名不能为空");
            return result;
        }
        // 用户表用不用修改
        // session中存的和提交上来的不一样那就要改
        String oldUserName = session.getAttribute("userName").toString();
        if (!StringUtils.equals(oldUserName, newUserName)) {
                result.put("success", false);
                result.put("message", "用户名称不能修改");
                return result;
        }
        String id = userInfo.getId();
        // id为空则为新增
        if (StringUtils.isBlank(id)) {
            userInfo.setId(UUID.randomUUID().toString().replace("-", ""));// 设置id
            userInfoService.addUserInfo(userInfo);
        } else {
            // 否则为更新
            userInfoService.updateUserInfoById(userInfo);
        }
        result.put("success", true);
        result.put("message", "保存成功");
        result.put("id", userInfo.getId());
        return result;
    }

    @RequestMapping("/uploadheadimg")
    @ResponseBody
    public Object uploadHeadImg(MultipartFile file, String id, HttpSession session) {
        JSONObject result = new JSONObject();
        result.put("success", true);
        result.put("message", "上传成功");
        result.put("id", id);
        String originalFilename = file.getOriginalFilename();
        String fileType = StringUtils.split(originalFilename, ".")[1];
        // 存储后文件的新名字
        String newName = UUID.randomUUID().toString().replace("-", "") + "." + fileType;
        File baseDir = new File(Constant.NGINX_IMAGES_PATH);
        if (!baseDir.exists()) {
                boolean isCreateSuccess = baseDir.mkdir();
        }
        String path = Constant.NGINX_IMAGES_PATH + newName;
        File savedFile = new File(path);
        try {
            boolean isCreateSuccess = savedFile.createNewFile();
            if (isCreateSuccess) {
                file.transferTo(savedFile);
            }
        } catch (IOException e) {
            LOGGER.error("头像上传-创建新文件失败:{}",e.getMessage());
            result.put("success", false);
            result.put("message", "头像上传失败");
        }
        // 将头像持久化进数据库
        if (result.getBooleanValue("success")) {// 图片转化成功的话
            // 如果转化成功url的地址
            String imagePath = Constant.NGINX_INTERNET_PRE + newName;
            // 图片的url返回去
            result.put("imagePath", imagePath);
            UserInfo userInfo = new UserInfo();
            userInfo.setImgPath(imagePath);
            // 传过来的id为空的话新建userinfo
            if (StringUtils.isBlank(id) || StringUtils.equals(id, "null")) {
                String newInfoId = UUID.randomUUID().toString().replace("-", "");
                userInfo.setId(newInfoId);
                userInfo.setUserName(session.getAttribute("userName").toString());
                // 存进数据库
                userInfoService.addUserInfo(userInfo);
                // id返回去
                result.put("id", newInfoId);
            } else {// 不为空update
                userInfo.setId(id);
                userInfoService.updateUserInfoById(userInfo);// 修改数据库
            }
        }
        return result;
    }

    /**
     * @Title: updatePassword
     * @Description: 修改密码
     * @param oldpass 旧密码
     * @param newpass 新密码
     * @param session 会话对象
     * @return 修改结果
     */
    @RequestMapping("/updatepassword")
    @ResponseBody
    public Object updatePassword(String oldpass, String newpass, HttpSession session) {
        JSONObject result = new JSONObject();
        String userName = session.getAttribute("userName").toString();
        User user = loginService.getUserByUserName(userName);
        String password = user.getPassword();
        if (!StringUtils.equals(password, oldpass)) {
            result.put("success", false);
            result.put("message", "旧密码不正确");
            return result;
        }
        user.setPassword(newpass);
        loginService.updateUserById(user);
        result.put("success", true);
        result.put("message", "修改成功");
        return result;
    }
}
